package zing.downloader.executor;

import zing.downloader.entity.Song;
import zing.downloader.interfaces.IDownloadFileImpl;
import zing.downloader.utils.DirectoryUtil;
import zing.downloader.utils.HtmlUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class DownloadFileImpl implements IDownloadFileImpl {

	@Override
	public void downloadSongToFile(Song song) {
        String songId = song.getVipId();
        String songName = song.getName();
        int songNumber = song.getNumber();

        String url = HtmlUtil.compoundLinkBySongId(songId);

        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection) (new URL(url).openConnection());

            httpURLConnection.setInstanceFollowRedirects(false);
            httpURLConnection.connect();

            String redirectedUrl = httpURLConnection.getHeaderField("Location");
            if (redirectedUrl.contains("?")) {
                redirectedUrl = redirectedUrl.substring(0, redirectedUrl.indexOf("?"));
            }

            URL mURL = new URL(redirectedUrl);
            URLConnection urlConnection = mURL.openConnection();
            InputStream in = urlConnection.getInputStream();
            String currentDir = DirectoryUtil.getDirectory();
            if (currentDir == null) {
                currentDir = "";
            }
            File songFile = new File(currentDir, songNumber + "." + songName + ".mp3");
            System.out.println("Downloading " + songFile.getName());
            FileOutputStream outputStream = new FileOutputStream(songFile);
            int read;
            byte[] bytes = new byte[2048];

            while ((read = in.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }

            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
